package com.giraffe.aiochat.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;
import com.giraffe.aiochat.server.handler.ReadCompletionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AIOServer {
    private static final Logger logger = LoggerFactory.getLogger(AIOServer.class);
    private static final int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
    private AsynchronousServerSocketChannel serverChannel;

    public void start() throws IOException {
        // 创建异步通道组（使用线程池）
        AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(THREAD_POOL_SIZE));

        serverChannel = AsynchronousServerSocketChannel.open(group);
        serverChannel.bind(new InetSocketAddress(8080));

        // 异步接受客户端连接
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel clientChannel, Void attachment) {
                // 继续监听新连接
                serverChannel.accept(null, this);

                try {
                    // 为新连接注册读取操作
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    String clientAddress = clientChannel.getRemoteAddress().toString();
                   
                    // 等待接收客户端的第一条消息（昵称）
                    clientChannel.read(buffer, buffer, new ReadCompletionHandler(clientChannel));

                    System.out.println("客户端已连接: " + clientAddress);
                } catch (IOException e) {
                    System.err.println("获取客户端地址失败: " + e.getMessage());
                }
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.err.println("接受连接失败: " + exc.getMessage());
            }
        });

        System.out.println("服务器启动，监听端口 8080");
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        new AIOServer().start();
        
        // 保持服务器运行
        Thread.currentThread().join();
    }
}